using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI;

namespace CodeStory.SmartUpload.WebControls
{
	[Designer(typeof(UploadManagerDesigner))]
	public class UploadManager : WebControl
	{
		public UploadManager() {
		}
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);
			ManagerID = Guid.NewGuid();
		}
		public Guid ManagerID {
			get {
				object obj = ViewState["ManagerID"];
				return obj == null ? Guid.NewGuid() : (Guid)obj;
			}
			set {
				object obj = ViewState["ManagerID"];
				if (obj != null) return;
				ViewState["ManagerID"] = value;
			}
		}
		public UploadFileCollection UploadFiles {
			get {
				SmartUploadContext c = SmartUploadContext.GetContext(Context);
				if (c == null) {
					return new UploadFileCollection();
				}
				return c.UploadFiles;
			}
		}
		protected override void CreateChildControls() {
			ChildControlsCreated = true;
			System.Web.UI.HtmlControls.HtmlGenericControl f = new System.Web.UI.HtmlControls.HtmlGenericControl("iframe");
			string url = string.Format("~/"+SmartConfiguration.TempFilePath+"/Progress.aspx?{0}={1}",SmartUploadContext.SMARTID_KEY, ManagerID.ToString("N"));
			f.Attributes.Add("src",ResolveClientUrl(url));
			Controls.Add(f);
		}
		protected override void OnPreRender(EventArgs e) {
			string queryString = Context.Request.Url.Query;
			if (string.IsNullOrEmpty(queryString)) {
				queryString = "?" + SmartUploadContext.SMARTID_KEY + "=" + ManagerID.ToString("N");
			} else {
				if (string.IsNullOrEmpty(Context.Request.QueryString[SmartUploadContext.SMARTID_KEY])) {
					queryString = queryString + "&" + SmartUploadContext.SMARTID_KEY + "=" + ManagerID.ToString("N");
				}
			}
			string url = Context.Request.Url.AbsolutePath.ToLower() + queryString;
			string script = string.Format(submitScript,Page.Form.ClientID,url);
			Page.ClientScript.RegisterOnSubmitStatement(GetType(),"CodeStory.Smart.Submit",script);

			base.OnPreRender(e);
		}
		string submitScript = @"
document.all.{0}.action = ""{1}"";
";
	}
}
